package com.hd.crdao.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.IDCardParams;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.hd.crdao.R;
import com.hd.crdao.base.BaseSecondActivity;
import com.hd.crdao.bean.BankDataBean;
import com.hd.crdao.bean.BankDetailBean;
import com.hd.crdao.bean.ChangeBindCardBean;
import com.hd.crdao.bean.MessageBean;
import com.hd.crdao.config.Config;
import com.hd.crdao.config.Constants;
import com.hd.crdao.proxy.RecognizeService;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.FileUtils;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.ExpandHeadView;
import com.hd.crdao.wrapper.CustomCallback;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import butterknife.BindView;

/**
 *
 *@author Programming
 *@date 2017/5/24 0024
 */
public class AddBankCardActivity extends BaseSecondActivity {
    public static final int TO_GET_BANKNAME = 100;
    private static final int RESULT_GETBANKNAME = 101;
    private static final int REQUEST_CODE_BANKCARD = 102;
    @BindView(R.id.addBankCard)
    ExpandHeadView mAddbankcard;
    @BindView(R.id.choosebank)
    TextView mChoosebank;
    @BindView(R.id.openbank)
    EditText mOpenbank;
    @BindView(R.id.banknumber)
    EditText mBanknumber;
    @BindView(R.id.btnSubmit)
    Button mBtnSubmit;
    @BindView(R.id.openbankName)
    EditText mOpenBankName;
    @BindView(R.id.recognizeBankCard)
    ImageView mRecognizeBankCard;
    public String mBankCode;
    public boolean mIsWannaData;


    @Override
    protected int setContentView() {
        return R.layout.activity_addbankcard;
    }

    @Override
    protected ExpandHeadView setExpandHeadView() {
        return mAddbankcard;
    }

    @Override
    protected void initView() {
        //从我要收款跳转过来,需要直接添加后返回信息
        mIsWannaData = getIntent().getBooleanExtra("isWannaData", false);
        //判断是添加还是修改
        boolean flag = getIntent().getBooleanExtra("flag", false);
        //bankid用于修改银行信息
        String bankid = getIntent().getStringExtra("bankid");
        initData(flag, bankid);
        initListener(flag, bankid);
    }

    /**
     * 初始化数据
     *
     * @param flag
     * @param bankid
     */
    private void initData(boolean flag, final String bankid) {
        if (flag && !TextUtils.isEmpty(bankid)) {
            mAddbankcard.getHeadViewMidText().setText("修改开户名");
            OkHttpUtils.post().url(Constants.QUERYBANKDETAIL_URL)
                    .addParams("data", bankid)
                    .addParams("sign", Constants.SIGN)
                    .build().execute(
                    new CustomCallback<BankDetailBean>() {
                        @Override
                        public void onResponse(BankDetailBean bankDetailBean, int id) {
                            if (bankDetailBean.getSuccess() == 0) {
                                BankDetailBean.DataBean data = bankDetailBean.getData();
                                mOpenbank.setText(data.getBcBankname());
                                mOpenbank.setFocusableInTouchMode(false);
                                mOpenBankName.setText(data.getBcName());
                                mChoosebank.setText(data.getBankCode().getBcNote());
                                mChoosebank.setOnClickListener(null);
                                mBanknumber.setText(data.getBcCardnum());
                                mBanknumber.setFocusableInTouchMode(false);
                            } else {
                                MyToast.show(bankDetailBean.getMessage());
                            }
                        }
                    });
        }
    }

    private void initListener(final boolean flag, final String bankid) {

        mChoosebank.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(UIUtils.getContext(), ChooseBankActivity.class), TO_GET_BANKNAME);
            }
        });
        mBtnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (flag && !TextUtils.isEmpty(bankid)) {
                    changeAccountName(bankid);
                } else {
                    checkAddBankCard();
                }
            }
        });
        mRecognizeBankCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initAccessToken();
                Intent intent = new Intent(UIUtils.getContext(), CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtils.getSaveFile(AddBankCardActivity.this).getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                        CameraActivity.CONTENT_TYPE_BANK_CARD);
                startActivityForResult(intent, REQUEST_CODE_BANKCARD);
            }
        });
    }

    /**
     * OCR识别--百度
     */
    private void initAccessToken(){
        OCR.getInstance().initAccessToken(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                // 调用成功，返回AccessToken对象
                String token = result.getAccessToken();
            }
            @Override
            public void onError(OCRError error) {
                // 调用失败，返回OCRError子类SDKError对象
            }
        }, getApplicationContext());
    }

    /**
     * 识别银行卡功能
     * @param filePath
     */
    private void recognizeBankId(String filePath) {
        // 身份证识别参数设置
        IDCardParams param = new IDCardParams();
        param.setImageFile(new File(filePath));


// 调用身份证识别服务
        RecognizeService.recBankCard(FileUtils.getSaveFile(getApplicationContext()).getAbsolutePath(),
                new RecognizeService.ServiceListener() {
                    @Override
                    public void onResult(String result) {
                        if(result!=null){
                            mChoosebank.setText(result.split(",")[0]);
                            mBanknumber.setText(result.split(",")[1]);
                            ALog.d(result);
                        }
                    }
                });
    }

    /**
     * 修改银行卡开户名
     *
     * @param bankid 银行卡ID
     */
    private void changeAccountName(String bankid) {
        String accountName = mOpenBankName.getText().toString().trim();
        if (TextUtils.isEmpty(accountName)) {
            MyToast.show("请填写开户名");
            return;
        }
        OkHttpUtils.post().url(Constants.UPDATECARDACCOUNTNAME_URL)
                .addParams("sign", Constants.SIGN)
                .addParams("businessCardId", bankid)
                .addParams("accountName", accountName)
                .build().execute(new CustomCallback<MessageBean>() {

            @Override
            public void onResponse(MessageBean messageBean, int id) {
                if (messageBean.getSuccess() == 0) {
                    MyToast.show(messageBean.getMessage());
                    onBackPressed();
                } else {
                    MyToast.show(messageBean.getMessage());
                }
            }
        });
    }

    /**
     * 添加银行卡--检查银行卡信息
     */
    private void checkAddBankCard() {
        String openbank = mOpenbank.getText().toString().trim();
        String banknumber = mBanknumber.getText().toString().trim();
        String accountName = mOpenBankName.getText().toString().trim();
        if (TextUtils.isEmpty(mBankCode) || TextUtils.isEmpty(openbank) || TextUtils.isEmpty(banknumber) || TextUtils.isEmpty(accountName)) {
            MyToast.show("填写的信息不能为空");
            return;
        } else {
            ALog.d("提交给服务器");
            submitForServer(mBankCode, openbank, banknumber, accountName);
        }
    }

    /**
     * 提交信息给服务器
     * @param bankCode  银行代码
     * @param openbank 开户行
     * @param banknumber 银行卡账号
     * @param accountName 用户名?
     */
    private void submitForServer(final String bankCode, final String openbank, String banknumber, final String accountName) {
      //  String url = Constants.BASEURL + "2033";
        String businessid = SPUtils.getString(Config.businessId, "");
        String data = businessid + "~" + bankCode + "~" + openbank + "~" + banknumber + "~0";
        //车商ID~银行代码ID~开户行~卡号~是否默认~开户行行号~缴费编号~银行协议编号
        //071c3e6096d34ffd8269d16402825a31~ABC~DF工商SAF~6212261402007712877~0
        OkHttpUtils.post().url(Constants.BINDBANKCARD_URL)
                .addParams("sign", Constants.SIGN)
                .addParams("data", data)
                .addParams("accountName", accountName)
                .build()
                .execute(new CustomCallback<ChangeBindCardBean>() {

                    @Override
                    public void onResponse(ChangeBindCardBean changeBindCardBean, int id) {
                        if (changeBindCardBean.getSuccess() == 0) {
                            MyToast.show(changeBindCardBean.getMessage());
                            if (mIsWannaData) {
                                BankDataBean bankDataBean = new BankDataBean();
                                bankDataBean.setBankNumber(bankCode);
                                bankDataBean.setAccountName(accountName);
                                bankDataBean.setBankName(openbank);
                                EventBus.getDefault().post(bankDataBean);
                                finish();
                            } else {
                                startActivity(new Intent(UIUtils.getContext(), MyBankCardActivity.class));
                                finish();
                            }
                        } else {
                            MyToast.show(changeBindCardBean.getMessage());
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == TO_GET_BANKNAME && resultCode == RESULT_GETBANKNAME) {
            String bankNmae = data.getStringExtra("bankNmae");
            mBankCode = data.getStringExtra("bankCode");
            mChoosebank.setText(bankNmae);
        }else if(requestCode==REQUEST_CODE_BANKCARD&&resultCode== Activity.RESULT_OK){
            recognizeBankId(FileUtils.getSaveFile(AddBankCardActivity.this).getAbsolutePath());
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    public void onBackPressed() {
        startActivity(new Intent(UIUtils.getContext(), MyBankCardActivity.class));
        finish();
    }
}
